Java TreeMap

In this tutorial, we will learn about java.util.TreeMap class, and its methods with explanation and working examples of it including custom key sorting.

TreeMap class

In Java, TreeMap is a class from the collections framework which is an implementation of the Map interface. This class gives a guarantee to the order, unlike the other classes of Map interface implementation. The order is based on the Comparator implementation logic or Comparable interface implemented by the Key class.

This class is not a thread-safe implementations, need to synchronize externally to make it thread-safe implementation.

This class provides all other basic operations such as contains, put ,get, remove and containsKey with the guaranteed constant time.

TreeMap Syntax

Syntax :

//Natural sorting order which is ascending
TreeMap<String> treeMap = new TreeMap<>();
//with custom Comparator sorting order
TreeMap<String> treeMap = TreeMap(Comparator<? super K> comparator)

TreeMap example with natural sort :

In this example, we will create a TreeMap with natural sorting order for map key type as String.

CopiedCopy Code
import java.util.TreeMap;
public class TreeMapNaturalOrder {
	public static void main(String[] args) {
		//tree map key as String will follow natural sort
		TreeMap<String,String> treeMap = new TreeMap<>();
		treeMap.put("Z", "Zebra");
		treeMap.put("Y", "Yak");
		treeMap.put("X", "Xiaosaurus");
		treeMap.put("W", "Wolf");
		//print all key and value pairs with natural sort
		System.out.println(treeMap);	
	}
}

Output:

{W=Wolf, X=Xiaosaurus, Y=Yak, Z=Zebra}

TreeMap example with custom sort

In this example, we will use custom sort by implementing Comparator interface over a user-defined class as a key.

CopiedCopy Code
import java.util.Comparator;
import java.util.TreeMap;
public class TreeMapCustomKeyExample {
	public static void main(String[] args) {
		Bank icici = new Bank("ICICI","India");
		Bank swiss = new Bank("Swiss","Switzerland");
		Bank bankofAmerica = new Bank("Bank of America","US");
		Bank citiGroup = new Bank("Citigroup","MultiNational");
		TreeMap<Bank,String> banks= new TreeMap<>(new Comparator<Bank>() {
			@Override
			public int compare(TreeMapCustomKeyExample.Bank o1, TreeMapCustomKeyExample.Bank o2) {
				//sort based on the bank name
				return o1.bankName.compareTo(o2.bankName);
			}
		}); 
		banks.put(icici, "Banking");
		banks.put(swiss, "Banking");
		banks.put(bankofAmerica, "Banking");
		banks.put(citiGroup, "Banking");
		System.out.println("Sorted based on Name : "+banks);
		TreeMap<Bank,String> bankSortLocation= new TreeMap<>(new Comparator<Bank>() {
			@Override
			public int compare(TreeMapCustomKeyExample.Bank o1, TreeMapCustomKeyExample.Bank o2) {
				//sort based on the bank name
				return o1.bankLocation.compareTo(o2.bankLocation);
			}
		});
		bankSortLocation.putAll(banks);
		System.out.println("Sorted based on location : "+bankSortLocation);
	}
	static class Bank {
		public String bankName;
		public String bankLocation;
		public Bank(String bankName, String bankLocation) {
			this.bankName = bankName;
			this.bankLocation = bankLocation;
		}
		@Override
		public int hashCode() {
			final int prime = 31;
			int result = 1;
			result = prime * result + ((bankLocation == null) ? 0 : bankLocation.hashCode());
			result = prime * result + ((bankName == null) ? 0 : bankName.hashCode());
			return result;
		}
		@Override
		public boolean equals(Object obj) {
			Bank other = (Bank) obj;
			if (bankLocation.equals(other.bankLocation) && bankName.equals(other.bankName))
				return true;
			return false;
		}
		@Override
		public String toString() {
			return "[bankName=" + bankName + ", bankLocation=" + bankLocation + "]";
		}
	}
}

Output :

Sorted based on Name : {[bankName=Bank of America, bankLocation=US]=Banking, [bankName=Citigroup, bankLocation=MultiNational]=Banking, [bankName=ICICI, bankLocation=India]=Banking, [bankName=Swiss, bankLocation=Switzerland]=Banking}
Sorted based on location : {[bankName=ICICI, bankLocation=India]=Banking, [bankName=Citigroup, bankLocation=MultiNational]=Banking, [bankName=Swiss, bankLocation=Switzerland]=Banking, [bankName=Bank of America, bankLocation=US]=Banking}

Explanation :

In the above example, we have created two TreeMap objects, both accept the keys as user-defined class Bank. We added four bank details, one TreeMap sort the order based on the bank name and another TreeMap sort with based on the bank location.

Both the sort order has been decided based on the custom Comparator implementation.

Conclusion :

In this tutorial, we have learned about the TreeMap and its methods along with the working examples including the user-defined key.